package icraf.carbon.gui.model;

import icraf.carbon.core.AbacusContainer;
import icraf.carbon.core.CostBenefitUnit;
import icraf.carbon.core.Project;

import java.awt.BorderLayout;
import java.util.ArrayList;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTabbedPane;
import javax.swing.event.ChangeListener;

public class ModelOutputEmissionNPVPanel extends JPanel {
	private static final long serialVersionUID = 1122919881488352700L;
	private JTabbedPane tabPanel;
	private Project project;
	private JLabel label = new JLabel();
	private ArrayList<ChangeListener> changeListenerList = new ArrayList<ChangeListener>();
	
	public AbacusContainer getProject() {
		return project;
	}
	
	public void setProject(Project project) {
		if (project == null)
			return;
		
		this.project = project;
	
		ArrayList<CostBenefitUnit> cbu = project.getCostBenefitUnitList();
		for (int i = 0; i < cbu.size(); i++) {
			IterationEmissionNPVPanel outPanel;
			if (i < tabPanel.getTabCount()) {
				outPanel = (IterationEmissionNPVPanel) tabPanel.getComponentAt(i);
				tabPanel.setTitleAt(i, cbu.get(i).getLabel());
			} else {
				outPanel = new IterationEmissionNPVPanel();
				tabPanel.addTab(cbu.get(i).getLabel(), outPanel);
				
				for(ChangeListener l: changeListenerList) {
					outPanel.addZoneTabListener(l);
				}
			}
			outPanel.setModelProject(project.getModelProject(), cbu.get(i));
		}
		int n = tabPanel.getTabCount() - cbu.size();
		for (int i = 0; i < n; i++) {
			tabPanel.remove(cbu.size());
		}
	}


	public ModelOutputEmissionNPVPanel() {
		tabPanel = new JTabbedPane();
		this.setLayout(new BorderLayout());
		this.add(tabPanel);
		this.add(label, BorderLayout.NORTH);
	}

	public String getLabel() {
		return label.getText();
	}

	public void setLabel(String label) {
		this.label.setText(label);
	}




	public void setCornerSetting(String unitDef, String unitArea, boolean isUnitSelectable) {
		for (int i = 0; i < tabPanel.getTabCount(); i++) {
			ModelOutputPanel c = (ModelOutputPanel) tabPanel.getComponentAt(i);
			c.setCornerSetting(unitDef, unitArea,isUnitSelectable);
			
		}
	}
	
	public void setZoneAreaScale(boolean isZoneAreaScale) {
		for (int i = 0; i < tabPanel.getTabCount(); i++) {
			ModelOutputPanel c = (ModelOutputPanel) tabPanel.getComponentAt(i);
			c.setZoneAreaScale(isZoneAreaScale);
		}
	}
	
	public void addZoneTabListener(ChangeListener l) {
		changeListenerList.add(l);
		for (int i = 0; i < tabPanel.getTabCount(); i++) {
			ModelOutputPanel c = (ModelOutputPanel) tabPanel.getComponentAt(i);
			c.addZoneTabListener(l);
		}
	}
	
	public void selectZoneTab(int idx) {
		for (int i = 0; i < tabPanel.getTabCount(); i++) {
			ModelOutputPanel c = (ModelOutputPanel) tabPanel.getComponentAt(i);
			c.selectZoneTab(idx);
		}
	}
}
